<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>App</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css"
      integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
      <a class="navbar-brand" href="#">App</a>
    </nav>

    <main role="main">
      <div class="jumbotron">
        <div class="container">
          <h1 class="display-3">Hello, world!</h1>
          <p>
            <a
              class="btn btn-primary"
              href="https://github.com/yanhaijing/template.js"
              role="button"
              >Learn more &raquo;</a
            >
          </p>
        </div>
      </div>
      <div class="container" id="container"></div>
    </main>
    <footer class="text-muted text-center">
      &copy;2013-2020 <a href="https://yanhaijing.com">颜海镜</a>
    </footer>
    <script src="./node_modules/template_js/dist/index.aio.js"></script>
    <script type="text/html" id="template">
      <h2>我的待办</h2>
      <ul>
        <%list.forEach(function(item, index) {%>
        <li>
          <div class="row">
            <div class="col-5 <%=index % 2 ? 'text-secondary' : ''%>">
              <%=item.text%>
            </div>
          </div>
        </li>
        <%})%>
      </ul>
      <a href="#" class="btn btn-dark add-todo">新增</a>
    </script>

    <script>
      class App {
        constructor(container) {
          this.container = container;
          this.tmpl = document.getElementById('template').innerHTML;
          this.data = {
            list: [
              {
                text: '预设待办a',
              },
              {
                text: '预设待办b',
              },
              {
                text: '预设待办c',
              },
            ],
          };
          this.bindEvent();
          this.render();
        }
        bindEvent() {
          const that = this;
          document.body.addEventListener('click', function (e) {
            if (e.target.className.indexOf('add-todo') !== -1) {
              e.preventDefault();
              that.data.list.push({
                text: '增加待办' + parseInt(Math.random() * 100, 10),
              });
              that.render();
            }
          });
        }
        render() {
          document.getElementById('container').innerHTML = template(
            this.tmpl,
            this.data,
          );
        }
      }

      new App();
    </script>
  </body>
</html>
